﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;

namespace StockFinder.Services.ChartPatterns
{
    /// <summary>
    /// Checks whether the last three weeks were tight closes
    /// </summary>
    public class ThreeWeekTightClosesChartPattern : IChartPattern
    {
        private const int BASE_LENGTH = 3;
        private const int BASE_DEPTH = 1;

        #region IChartPattern Members

        public ChartPatternResult Apply(Symbol symbol)
        {
            ChartPatternResult result = new ChartPatternResult();
            result.DoesFit = false;

            //check we have enough prices
            if (symbol.WeeklyPrices.Count >= BASE_LENGTH)
            {
                #region Get Weekly Price data

                //list is sorted in latest week first
                WeeklyPrice firstWeekPrices = symbol.WeeklyPrices[2];

                WeeklyPrice secondWeekPrices = symbol.WeeklyPrices[1];

                WeeklyPrice thirdWeekPrices = symbol.WeeklyPrices[0];

                #endregion

                #region Get weekly closes

                //get week close prices
                decimal firstWeekClose = firstWeekPrices.GetWeeklyClose();

                decimal secondWeekClose = secondWeekPrices.GetWeeklyClose();

                decimal thirdWeekClose = thirdWeekPrices.GetWeeklyClose();

                #endregion

                #region Get % differences

                //find difference between first and second week
                decimal firstDifference = (Math.Abs(secondWeekClose - firstWeekClose) / firstWeekClose)*100;

                //then find the difference between second and third
                decimal secondDifference = (Math.Abs(thirdWeekClose - secondWeekClose) / secondWeekClose)*100;

                #endregion

                #region Check pattern fit

                //check that both weeks are within boundaries i.e.
                result.DoesFit = ((firstDifference <= BASE_DEPTH) && (secondDifference <= BASE_DEPTH));

                #endregion
            }

            return result;
        }

        #endregion
    }
}
